package math;

import java.util.Arrays;

import math.Averagers.Averager;
import math.Averagers.Median;

import ui.TimeSeriesName;

/**
 * Averages over another {@link StatisticProvider}. 
 * 
 * @author Oliver Duerr
 */
public class SimpleAverager extends AbstractStatsProvider {

	private final StatisticProvider innerProvider;
	
	private final Averager averager;


	public SimpleAverager(StatisticProvider innerProvider, Averager averager) {
		this.innerProvider = innerProvider;
		this.averager = averager;
	}
	
	@Override
	public TimeSeriesName getName(String name) {
		TimeSeriesName innerName = innerProvider.getName(null);
		return new TimeSeriesName(innerName.getType(), name, innerName.getName() + " [" + averager.getName() + "]");
	}
	
	
	@Override
	void doWork() {
		long start = System.currentTimeMillis();
		int pointsToAverage = 20; 
		long[] rawTimes = innerProvider.getTimes();
		double[] rawValues = innerProvider.getValues();
		if (rawValues.length < pointsToAverage) {
			return; //TODO handle problem
		}
		times = new long[rawTimes.length - pointsToAverage];
		values = new double[rawTimes.length - pointsToAverage];
		int ii = 0;
		for (int i = pointsToAverage / 2; i < rawValues.length - pointsToAverage / 2; i++) {
			double[] valuesAvg = new double[pointsToAverage];
			int c = 0;
			for (int j = i - pointsToAverage / 2; j < i + pointsToAverage / 2; j++) {
				valuesAvg[c++] = rawValues[j];   
			}
			values[ii] = averager.getAverage(valuesAvg);
			times[ii] = rawTimes[i]; 
			ii++;
		}
		System.err.println("Time for calculating the average " + (System.currentTimeMillis() - start));
	}

	public static double median(double a[]) {
		double[] b = new double[a.length];
		System.arraycopy(a, 0, b, 0, b.length);
    	Arrays.sort(b);
    	if (b.length % 2 == 0) {
    		return (b[(b.length / 2) - 1] + b[b.length / 2]) / 2.0;
    	} else {
    		return b[b.length / 2];
    	}
	}

}
